<template>
  <el-select :value="sLabel" :disabled="disabled" filterable clearable :placeholder="$t('请选择')" @change="changeHandle($event)">
    <el-option
      v-for="item in investOptions"
      :key="item.id"
      :label="item.userName"
      :value="item.id"
    />
  </el-select>
</template>

<script>
import { findInvestByFundId, getFundInvestor } from '@/api/fund/investor/fundInvestor'
export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    // 基金ID
    fundId: {
      type: String,
      default: () => ''
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      svalue: this.value,
      investOptions: [],
      sLabel: ''
    }
  },
  watch: {
    fundId: {
      handler(val) {
        if (val) {
          this.findInvestByFundId(val)
        }
      },
      deep: true,
      immediate: true
    },
    value: {
      handler(newVal) {
        this.$nextTick(() => {
          this.svalue = newVal
          if (this.investOptions && this.investOptions.length > 0) {
            if (this.svalue) {
              this.getName(this.svalue)
            }
          }
        })
      },
      immediate: true
    },
    svalue: {
      handler(val) {
        if (val) {
          this.$emit('input', val)
        } else {
          this.sLabel = undefined
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  methods: {
    findInvestByFundId(id) {
      findInvestByFundId(id).then(res => {
        this.$nextTick(() => {
          this.investOptions = res.data
          if (this.svalue) {
            this.getName(this.svalue)
          }
        })
      })
    },
    getName(value) {
      if (value !== undefined && value !== null && this.investOptions !== undefined && this.investOptions !== null) {
        const data = this.investOptions.find(item => item.id === value)

        if (data) {
          this.sLabel = data.userName
        } else {
          getFundInvestor(value).then((res) => {
            if (res.code === 200 && res.data) {
              this.sLabel = res.data.userName
            }
          })
        }
      }
    },
    changeHandle(e) {
      this.svalue = e
      if (this.svalue) {
        this.getName(this.svalue)
      }
      this.$emit('input', this.svalue)
      this.$emit('change', this.svalue)
    }
  }
}
</script>
